package com.syc.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.syc.entity.Configuration;
import com.syc.io.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 解析config.xml
 *
 * @author Shen Yu Chen
 * @create 2020-04-23
 **/
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    //dom4j解析config.xml,封装到Configuration
    public Configuration pareConfig(InputStream in) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(in);
        //<configuration>
        Element rootElement = document.getRootElement();
        //<property> 使用"//"从匹配选择的当前节点选择文档中的节点，而不考虑它们的位置
        List<Element> propertyList = rootElement.selectNodes("//property");
        //封装config文件中的键值对配置参数
        Properties properties = new Properties();
        for (Element property : propertyList) {
            String name = property.attributeValue("name");
            String value = property.attributeValue("value");
            properties.setProperty(name, value);
        }

        //使用连接池复用连接资源,避免资源浪费
        //及频繁创建销毁连接造成的性能消耗
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        //dom4j解析config中配置的mapper.xml路径转成字节输入流
        //调用mapperBuilder解析mapper.xml
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsSteam);
        }

        return configuration;
    }
}
